package com.hyjx.framework.service.word;


import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFHeader;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author tiank
 * date 2017-08-11
 * desc  导出word文件的工具类，具体使用方法参考论坛中相关工具类的使用方法
 */

public class WordService {
    /**
     * 替换段落里面的变量
     *
     * @param doc    要替换的文档
     * @param params 参数 要替换的内容和替换之后的值
     */
    private void replaceInPara(XWPFDocument doc, Map<String, Object> params) {
        Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator();
        XWPFParagraph para;
        while (iterator.hasNext()) {
            para = iterator.next();
            this.replaceInPara(para, params);
        }
    }
    
    /**
     * 替换段落里面的变量
     *
     * @param para   要替换的段落
     * @param params 要替换的内容和替换之后的值
     */
    private void replaceInPara(XWPFParagraph para, Map<String, Object> params) {
        List<XWPFRun> runs;
        Matcher matcher;
        if (this.matcher(para.getParagraphText()).find()) {
            runs = para.getRuns();
            int start = -1;
            int end = -1;
            String str = "";
            for (int i = 0; i < runs.size(); i++) {
                XWPFRun run = runs.get(i);
                String runText = run.toString();
                if ('$' == runText.charAt(0) && '{' == runText.charAt(1)) {
                    start = i;
                }
                if ((start != -1)) {
                    str += runText;
                }
                if ('}' == runText.charAt(runText.length() - 1)) {
                    if (start != -1) {
                        end = i;
                        break;
                    }
                }
            }
            //System.out.println("start--->"+start);
            // System.out.println("end--->"+end);
            
            // System.out.println("str---->>>" + str);
            
            for (int i = start; i <= end; i++) {
                para.removeRun(i);
                i--;
                end--;
                //  System.out.println("remove i="+i);
            }
            
            for (String key : params.keySet()) {
                if (str.equals(key)) {
                    para.createRun().setText((String) params.get(key));
                    break;
                }
            }
        }
    }
    
    /**
     * 替换表格里面的变量
     *
     * @param doc    要替换的文档
     * @param params 参数 要替换的内容和替换之后的值
     */
    private void replaceInTable(XWPFDocument doc, Map<String, Object> params, String tltles[], List<Map<String, String>> list) {
        Iterator<XWPFTable> iterator = doc.getTablesIterator();
        XWPFTable lastTable = null;
        XWPFTable table;
        List<XWPFTableRow> rows;
        List<XWPFTableCell> cells;
        List<XWPFParagraph> paras;
        while (iterator.hasNext()) {
            table = iterator.next();
            lastTable = table;
            rows = table.getRows();
            for (XWPFTableRow row : rows) {
                cells = row.getTableCells();
                for (XWPFTableCell cell : cells) {
                    paras = cell.getParagraphs();
                    for (XWPFParagraph para : paras) {
                        this.replaceInPara(para, params);
                    }
                }
            }
        }
        //String titles[],List<Map<String,String>> list, XWPFTable table
        try {
            testWriteTable(tltles, list, lastTable);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    /**
     * 正则匹配字符串
     *
     * @param str
     * @return
     */
    private Matcher matcher(String str) {
        Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(str);
        return matcher;
    }
    
    /**
     * 关闭输入流
     *
     * @param is
     */
    private void close(InputStream is) {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * 关闭输出流
     *
     * @param os
     */
    private void close(OutputStream os) {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    
    /**
     * titles 对应的map中的key，
     *
     * @throws Exception
     */
    private void testWriteTable(String titles[], List<Map<String, String>> list, XWPFTable table) throws Exception {
        List<XWPFTableRow> rows = table.getRows();
        XWPFTableRow row;
        List<XWPFTableCell> cells;
        XWPFTableCell cell;
        int rowSize = list.size();
        int cellSize;
        for (int i = 0; i < rowSize; i++) {
            row = table.createRow();
            cells = row.getTableCells();
            cellSize = cells.size();
            for (int j = 0; j < cellSize; j++) {
                //写内容
                Map<String, String> map = list.get(i);
                cell = cells.get(j);
                CTTc cttc = cell.getCTTc();
                CTTcPr cellPr = cttc.addNewTcPr();
                cell.setText(map.get(titles[j]));//内容
            }
        }
        
    }
    
    private static void main(String[] args) {
    
    }
    
    /**
     * @param response
     * @param params             要替换的内容以及向对应的替换的值
     * @param fileNameInResource 模板文件路径   "d://sta.docx"
     * @param tltles             list数据map中的key
     * @param list               list数据
     */
    private void createWord(HttpServletResponse response, Map<String, Object> params, String fileNameInResource, String tltles[], List<Map<String, String>> list) {
        try {
            
            XWPFDocument doc;
            InputStream is;
            is = new FileInputStream(new File(fileNameInResource));
            doc = new XWPFDocument(is);
            //
            this.replaceInPara(doc, params);
            //替换表格里面的变量
            this.replaceInTable(doc, params, tltles, list);
            this.replaceHeader(doc, params);
            
            
            //String titles[],List<Map<String,String>> list, XWPFTable table
            //testWriteTable(tltles,list);
            
            OutputStream os = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=test.docx");
            doc.write(os);
            this.close(os);
            this.close(is);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //  public void replaceInPara(XWPFParagraph para, Map<String, Object> params)
    
    /**
     * 替换页眉内容
     *
     * @param doc
     * @param params
     */
    private void replaceHeader(XWPFDocument doc, Map<String, Object> params) {
        
        List<XWPFHeader> list = doc.getHeaderList();
        for (int i = 0; i < list.size(); i++) {
            XWPFHeader header = list.get(i);
            List<XWPFParagraph> xWPFParagraphs = header.getParagraphs();
            for (XWPFParagraph para : xWPFParagraphs) {
                this.replaceInPara(para, params);
            }
        }
    }
}